package main

import (
	"fmt"
	"net"
	"time"
)

func handleConnection(clientConn net.Conn, targetHost string, targetPort int) {
	defer clientConn.Close()
	targetConn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", targetHost, targetPort), 5*time.Second)
	if err != nil {
		fmt.Printf("Error connecting to target server: %s\n", err)
		return
	}
	defer targetConn.Close()

	go copyData(clientConn, targetConn)
	go copyData(targetConn, clientConn)
}

func copyData(source, target net.Conn) {
	defer source.Close()
	buf := make([]byte, 4096)
	for {
		n, err := source.Read(buf)
		if err != nil {
			fmt.Printf("Error reading from source: %s\n", err)
			break
		}
		_, err = target.Write(buf[:n])
		if err != nil {
			fmt.Printf("Error writing to target: %s\n", err)
			break
		}
	}
}

func main() {
	listener, err := net.Listen("upd", ":8080") // 本地监听端口
	if err != nil {
		fmt.Printf("Error listening: %s\n", err)
		return
	}
	defer listener.Close()

	fmt.Println("Listening on :8080")
	for {
		clientConn, err := listener.Accept()
		if err != nil {
			fmt.Printf("Error accepting: %s\n", err)
			continue
		}
		go handleConnection(clientConn, "103.61.37.134", 45000) // 假设代理到本地的8081端口
	}
}
